<?php

require_once('publiccontroller.php');

class Contact extends PublicController
{
	function Contact()
	{
		parent::PublicController();
		$this->set_page_title('Contact');
		$this->load->helper('form');
	}

	function index()
	{
		$data['name'] = '';
		$data['email'] = '';
		$data['message'] = '';
		$data['security_code'] = $this->_get_security_code();
		$this->_display('index', $data);
	}

	function submit()
	{
		$name = isset($_POST['name']) ? clean_str($_POST['name']) : null;
		$email = isset($_POST['email']) ? clean_str($_POST['email']) : null;
		$message = isset($_POST['message']) ? clean_str($_POST['message']) : null;
		$security_code_ok = $_POST['check_security_code'] == $_POST['user_security_code'];
		$errors = array();
		if (!$name) $errors[] = 'Vous devez indiquer votre nom';
		if (!check_email($email)) $errors[] = 'Votre adresse e-mail est invalide';
		if (!$message) $errors[] = 'Vous devez indiquer un message';
		if (!$security_code_ok) $errors[] = "Le code de sécurité n'est pas bon";

		$data = array();
		if (count($errors) == 0) {
			$this->load->library('email');
			$this->email->from($email);
			$this->email->to(CONTACT_EMAIL);
			$this->email->subject('Site Miage : message de '.$name);
			$this->email->message($message);
			$data['name'] = '';
			$data['email'] = '';
			$data['message'] = '';
			if ($this->email->send()) {
				$data['success_notice'] = 'Votre message a été envoyé !';
			}
			else {
				$data['warning_notice'] = "Impossible d'envoyer votre message";
			}
		}
		else {
			$data['name'] = $name;
			$data['email'] = $email;
			$data['message'] = $message;
			$data['error_notice'] = $errors;
		}
		$data['security_code'] = $this->_get_security_code();
		$this->_display('index', $data);
	}

	function _get_security_code()
	{
		return security_code();
	}
}
